package com.xxxx.seckill.utils;


import net.sf.jsqlparser.expression.operators.relational.GreaterThanEquals;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;


/*
* Cookie工具类
* */
public final class CookieUtil {

    public static String getCookieValue(HttpServletRequest request,String cookieName){
        return getCookieValue(request,cookieName,false);
    }

/*
*
* @param isDecoder是否需要URL编码
* */
    public static String getCookieValue(HttpServletRequest request,String cookieName,boolean isDecoder){
//        根据请求获取客户端提交的所有cookie，设置cookie使用addCookie
        Cookie[] cookieList = request.getCookies();
//        判断，获取到的cookie列表和参数cookieName是不是为空
        if (cookieList==null || cookieName==null){
            return null;
        }
        String retValue=null;
        try{
            for (int i=0;i<cookieList.length;i++){
            if(cookieList[i].getName().equals(cookieName)){
//                需要编码
                if(isDecoder){
                    retValue= URLDecoder.decode(cookieList[i].getValue(),"UTF-8");
//                不需要编码
                }else {
                    retValue=cookieList[i].getValue();

                }
                break;
            }
        }
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }

        return retValue;
    }


    public static String getCookieValue(HttpServletRequest request,String cookieName,String encodeString) {
//        根据请求获取cookie
        Cookie[] cookieList = request.getCookies();
//        判断，获取到的cookie列表和参数cookieName是不是为空
        if (cookieList == null || cookieName == null) {
            return null;
        }
        String retValue = null;
        try {
            for (int i = 0; i < cookieList.length; i++) {
//                如果获取到的名和参数相等，直接对value进行URL编码
                if (cookieList[i].getName().equals(cookieName)) {
                    retValue=URLDecoder.decode(cookieList[i].getValue(),encodeString);
                    break;
                }
            }
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }

        return retValue;
    }

    public static void setCookie(HttpServletRequest request, HttpServletResponse response,String cookieName,
                                 String cookieValue){
        setCookie(request,response,cookieName,cookieValue,-1);
    }
/*
* @param cookieMaxage标识Cookie失效时间，单位为秒，为正数则标识在大于指定时间后失效，为0表示删除，为-1表示关闭浏览器即失效
* */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response,String cookieName,
                                 String cookieValue,int cookieMaxage){
        setCookie(request,response,cookieName,cookieValue,false);
    }

    public static void setCookie(HttpServletRequest request, HttpServletResponse response,String cookieName,
                                 String cookieValue,boolean isEncode){
        setCookie(request,response,cookieName,cookieValue,-1,isEncode);
    }

    public static void setCookie(HttpServletRequest request, HttpServletResponse response,String cookieName,
                                 String cookieValue,int cookieMaxage,boolean isEncode){
        dosetCookie(request,response,cookieName,cookieValue,cookieMaxage,isEncode);
    }

    public static void setCookie(HttpServletRequest request, HttpServletResponse response,String cookieName,
                                 String cookieValue,int cookieMaxage,String encodeString){
        dosetCookie(request,response,cookieName,cookieValue,cookieMaxage,encodeString);
    }
    public static void deleteCookie(HttpServletRequest request,HttpServletResponse response,String cookieName){
        dosetCookie(request,response,cookieName,"",-1,false);
    }

    private static final void dosetCookie(HttpServletRequest request,HttpServletResponse response,String cookieName,
                                          String cookieValue,int cookieMaxage,boolean isEncode){
        try {
            if(cookieValue==null){
                cookieValue="";
            }else if(isEncode){
                cookieValue = URLEncoder.encode(cookieValue, "UTF-8");
            }
            Cookie cookie = new Cookie(cookieName,cookieValue);
            if (cookieMaxage>0){
                cookie.setMaxAge(cookieMaxage);
            }
            if (null!=request){
                String domainName = getDomainName(request);
                System.out.println(domainName);
                if (!"localhost".equals(domainName)){
                    cookie.setDomain(domainName);
                }
            }
            cookie.setPath("/");
            response.addCookie(cookie);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /*
    * 设置Cookie的值，并使其在指定时间内生效，cookieMaxage标识cookie生效的最大秒数
    * */
    private static final void dosetCookie(HttpServletRequest request,HttpServletResponse response,String cookieName,
                                          String cookieValue,int cookieMaxage,String encodeString){
        try {
            if (cookieValue==null){
                cookieValue="";
            }else {
                cookieValue= URLEncoder.encode(cookieValue,encodeString);
            }
            Cookie cookie = new Cookie(cookieName,cookieValue);
            if (cookieMaxage>0){
                cookie.setMaxAge(cookieMaxage);
            }
            if (null!=request){
                String domainName = getDomainName(request);
                System.out.println(domainName);
                if (!"localhost".equals(domainName)){
                    cookie.setDomain(domainName);
                }
            }
            cookie.setPath("/");
            response.addCookie(cookie);

        }catch (Exception e){
            e.printStackTrace();
        }
    }
/*
* 获取Cookie的域名
*
* */
    private static final String getDomainName(HttpServletRequest request) {
        String domainName=null;
        String serverName = request.getRequestURL().toString();
        if (serverName==null||serverName.equals("")){
            domainName="";
        }else {
//            把全路径的字符串改为小写
            serverName = serverName.toLowerCase();
//            如果字符串是以http://开头
            if (serverName.startsWith("http://")){
//                截取第七个字符及以后的字符
                serverName = serverName.substring(7);
            }
            int end = serverName.length();
//            如果包含/字符，返回第一次出现的位置
            if(serverName.contains("/")){
                end=serverName.indexOf("/");
            }
//            名字就是从头到第一处出现/的位置
            serverName = serverName.substring(0, end);
//            根据.进行分割，比如www.baidu,com
            final String[] domains = serverName.split("\\.");
            int len = domains.length;
//            www.xxx.com.cn
            if (len>3){
                domainName=domains[len-3]+"."+domains[len-2]+"."+domains[len-1];
//            xxx.com
            }else if(len<3&&len>1){
                domainName=domains[len-2]+"."+domains[len-1];
//            xxx
            }else {
                domainName=serverName;
            }
        }
//        使用冒号分隔，假如localhost:8080，把8080丢掉
        if (domainName!=null&&domainName.indexOf(":")>0){
            String[] ary = domainName.split("\\:");
            domainName=ary[0];
        }

        return domainName;
    }

}
